<template>
  <div style="min-height: 76vh">
    <el-form @keyup.enter.native="getData()" :inline="true">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="主体名称"
          @keyup.enter.native="getData()"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          auto-top
          clearable
          placeholder="地区选择"
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button type="primary" icon="el-icon-upload2" @click="handleUpload()">导入</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleDownload()"
        >
          导出
        </el-button>
        <el-button @click="handleEdit" icon="el-icon-plus" type="primary">新增主体</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:business="scope">
        <div class="text-truncate" :title="scope.row.business_scope">
          {{ scope.row.business_scope }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <new-cmpt
      :visible.sync="newVisible"
      :customer-related-id="customerRelatedId"
      :project-type="1"
      @success="getData(params.index)"
    ></new-cmpt>
    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入主体信息"
      :post-api="postUrl"
      excel-template="/static/files/主体信息导入模板(常规).xlsx"
      @success="getData(params.index)"
    ></import-excel>
  </div>
</template>

<script>
import {
  // enumCustomerSource,
  enumApprovalStatus,
  enumOrgClass,
  // enumCreditType
} from '@/credit/plugins/enum'
import NewCmpt from './New'
import ImportExcel from '@/components/ImportExcel'
// import { queryUrl } from '@vimi/utils-tool'
import SelectAddress from '@/components/select/SelectAddress'
import { queryTrouble } from '@vimi/utils-api'
export default {
  components: {
    NewCmpt,
    SelectAddress,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      enumOrgClass,
      postUrl: '',
      dialogImportVisible: false,
      exportLoading: false,
      enumApprovalStatus,
      newVisible: false,
      customerRelatedId: '',
      // api表
      tableName: 'customer_related',
      tableId: '',
      params: {
        index: 1,
        size: 15,
        'project_type.eq': '1',
        customer_name: '',
        address_code: '',
      },
      loading: false,
      submit_type: '',
      // 表格
      tableData: [],
      tableCount: 0,
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '100px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address', minWidth: '150px' } },
        {
          attrs: { label: '组织形式', prop: 'org_class', align: 'center' },
          process: v => enumOrgClass[v] || '-',
        },
        { attrs: { label: '负责人', prop: 'corp_name' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        {
          attrs: { label: '经营范围', prop: 'business_scope', minWidth: '100px' },
          slot: 'business',
        },
        { attrs: { label: '申请金额', prop: 'apply_funds' } },
        { attrs: { label: '创建用户', prop: 'submit_person_name' } },
        { attrs: { label: '创建时间', prop: 'create_time' } },
        {
          attrs: { label: '操作', align: 'center', minWidth: '100px' },
          operations: [
            { content: '修改', icon: 'fa fa-edit', event: this.handleEdit },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
            },
          ],
        },
      ],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.postUrl =
      '/api/credit/import/' +
      queryTrouble(this.tableName, {
        importKey: `${this.tableName}_regular_template`,
        'service_id.eq': this.$store.getters.org.clientId,
        'submit_type.eq': 1,
        'project_type.eq': 1,
      })
    this.submit_type = this.$utils.getClientOrgClass() === 'org_gov_ny' ? '1' : '4'
    this.params.address_code = this.$utils.getAddressCode()
    this.getData()
  },
  mounted() {},
  methods: {
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.newVisible = false
      this.params['submit_type.eq'] = this.submit_type

      let [res, err] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, this.params, { create_time: 'desc' })
      )
      this.loading = false
      if (err) {
        return this.$message.error('获取经营主体失败，请稍后重试！')
      }

      const data = res.data.data || []
      this.tableData = data.map(d => {
        d.approvalStatus = enumApprovalStatus[d.is_approval] || {}
        return d
      })
      this.tableCount = res.data.totalCount
    },
    onNew() {
      this.customerRelatedId = ''
      this.newVisible = true
    },
    handleEdit(row) {
      this.customerRelatedId = ''
      // this.formData = row || {}
      this.customerRelatedId = row ? row.customer_related_id : ''
      this.newVisible = true
    },
    async handleDelete(row) {
      this.$msgbox({
        title: '提示',
        message: `确定删除主体：${row.customer_name}?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '删除中...'
            instance.confirmButtonLoading = true
            const [res, err] = await this.$utils.promise(
              this.$api.deleteData('credit', 'customer_related', row.customer_related_id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'

            if (res) {
              this.$message.success('删除成功！')
              this.getData()
            } else {
              if (err.status === 403) {
                this.$message.error(`删除失败！没有权限删除该主体`)
              } else {
                this.$message.error(`删除失败！${err.status}`)
              }
            }

            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    handleUpload() {
      this.dialogImportVisible = true
    },

    async handleDownload() {
      const { index, size, ...params } = this.params // eslint-disable-line
      const exportParams = {
        service: this.$serviceName,
        table: this.tableName,
        params: params,
        filename: '主体信息.xlsx',
      }

      this.exportLoading = true
      await this.$utils.promise(this.$api.exportData(exportParams))
      this.exportLoading = false
    },
  },
}
</script>

<style lang="scss" scoped></style>
